﻿using System;
using WiMo.Games;
using WiMo.Games.Drawables;
using WiMo.Games.Inputs;
using WiMo.Games.Audio;

namespace Gravity
{
    class Game : IGame
    {
        ISpriteImage _ball;
        IGameAudio _blip;

        public Game(IGameEngine engine)
        {
            Engine = engine;
            Engine.ContentManager.ContentLocation = "Content";
            Engine.Display.BackgroundColor = Color.Yellow;
            Engine.DiagnosticsFontColor = Color.Black;
            Engine.EnableDiagnostics = true;        
        }

        public void Initialize()
        {
            Engine.PhysicsManager.Gravity = new Vector2(0, 10);
            Engine.InputManager.RightSoftButton = "Exit";
        }

        public void BeginRun(){}
        public void CreateMenus() {}

        public void LoadContent()
        {            
            _ball = Engine.ContentManager.LoadImage("Ball.png");
            _ball.Position = new PointF(Engine.Display.TargetSize.Width / 2, 30);                
            _ball.Force = Vector2.Zero;
            _ball.AffectedByGravity = true;
            _ball.ColorKey = Color.White;
            _ball.CoefRestitution = 0.9f;
            _ball.Collision += ball_Collision;
            _ball.CollisionManagement = CollisionManagement.Auto;
            Engine.PhysicsManager.Add(_ball);
            Engine.CollisionManager.Add(_ball);

            _blip = Engine.AudioManager.LoadSound("blip.wav");
        }

        void ball_Collision(object sender, CollisionEventArgs e)
        {
            Engine.Vibrate(5);
            _blip.Play();
        }

        private IInputManager _lastState;

        public void Update(GameTime gameTime)
        {
            if (Engine.InputManager.IsKeyDown(Keys.Return))
                Engine.Exit();

            if (Engine.InputManager.IsKeyDown(Keys.RightSoftButton))
                Engine.Exit();

            if (Engine.InputManager.WasPressed(_lastState, Keys.Right))
            {
                _ball.Force = Vector2.Zero;
                _ball.Position = new PointF(Engine.Display.TargetSize.Width / 2, 30);
            }

            _lastState = Engine.InputManager.GetKeysState();

            Engine.PhysicsManager.Update(gameTime);
        }

        public void Draw(GameTime gameTime)
        {
            Engine.Display.Add(_ball);
        }

        public bool CanExit()
        {
            return true;
        }

        public IGameEngine Engine {get; set;}
    }
}
